import path from 'path';
import * as fs from 'fs';

const DATA_DIR = path.join(process.cwd(), 'excel', '06-21');

interface TableDefinition {
  tableName: string;
  tableCode: string;
  description: string;
  fields: Array<{
    sequence: string;
    name: string;
    example: string;
    dataType: string;
    measurementClass: string;
    dataSource: string;
  }>;
}

function parseCSVFile(filename: string): TableDefinition[] {
  const filePath = path.join(DATA_DIR, filename);
  if (!fs.existsSync(filePath)) {
    console.warn(`文件不存在: ${filePath}`);
    return [];
  }

  let contentBuffer = fs.readFileSync(filePath);
  // 处理 BOM
  if (contentBuffer[0] === 0xEF && contentBuffer[1] === 0xBB && contentBuffer[2] === 0xBF) {
    contentBuffer = contentBuffer.subarray(3);
  }

  const content = contentBuffer.toString('utf-8');
  const lines = content.split('\n').map(line => line.trim()).filter(line => line);
  
  const tables: TableDefinition[] = [];
  let currentTable: TableDefinition | null = null;
  let expectingHeader = true;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const columns = line.split(',').map(col => col.trim());

    // 检查是否是表头行（包含"表 C."）
    if (line.includes('表 C.') || line.includes('表C.')) {
      // 保存之前的表
      if (currentTable) {
        console.log(`完成表: ${currentTable.tableName}, 字段数: ${currentTable.fields.length}`);
        if (currentTable.tableName === 'table_c81') {
          console.log('table_c81 字段列表:');
          currentTable.fields.forEach((field, index) => {
            console.log(`  ${index + 1}. ${field.name} (${field.dataType})`);
          });
        }
        tables.push(currentTable);
      }

      // 解析表名信息
      const tableInfo = columns[0];
      console.log(`\n解析表头: ${tableInfo}`);
      const match = tableInfo.match(/表\s*C\.?(\d+)\s+([A-Z]+\d+)\s+(.+)/);
      
      if (match) {
        const [, tableNumber, tableCode, description] = match;
        currentTable = {
          tableName: `table_c${tableNumber}`,
          tableCode: tableCode,
          description: description,
          fields: []
        };
        console.log(`创建新表: ${currentTable.tableName} - ${description}`);
        expectingHeader = true;
      }
      continue;
    }

    // 检查是否是列名行
    if (expectingHeader && columns[0] === '序号' && columns[1] === '中文名称') {
      console.log(`找到列名行: ${line}`);
      expectingHeader = false;
      continue;
    }

    // 处理字段定义行
    if (currentTable && !expectingHeader && columns.length >= 6) {
      const sequence = columns[0];
      const name = columns[1];
      const example = columns[2];
      const dataType = columns[3];
      const measurementClass = columns[4];
      const dataSource = columns[5];

      // 跳过空行或无效行
      if (sequence && name && sequence !== '序号') {
        console.log(`添加字段到 ${currentTable.tableName}: ${name}`);
        currentTable.fields.push({
          sequence,
          name,
          example,
          dataType,
          measurementClass,
          dataSource
        });
      }
    }
  }

  // 添加最后一个表
  if (currentTable) {
    console.log(`完成最后一个表: ${currentTable.tableName}, 字段数: ${currentTable.fields.length}`);
    if (currentTable.tableName === 'table_c81') {
      console.log('table_c81 字段列表:');
      currentTable.fields.forEach((field, index) => {
        console.log(`  ${index + 1}. ${field.name} (${field.dataType})`);
      });
    }
    tables.push(currentTable);
  }

  return tables;
}

function main() {
  console.log('调试 table_c81 解析过程...\n');
  
  const tables = parseCSVFile('属性表-基础参数表.csv');
  
  console.log(`\n总共解析了 ${tables.length} 个表`);
  
  // 查找 table_c81
  const table81 = tables.find(t => t.tableName === 'table_c81');
  if (table81) {
    console.log(`\ntable_c81 详细信息:`);
    console.log(`表名: ${table81.tableName}`);
    console.log(`表代码: ${table81.tableCode}`);
    console.log(`描述: ${table81.description}`);
    console.log(`字段数: ${table81.fields.length}`);
    
    // 检查重复字段
    const fieldNames = table81.fields.map(f => f.name);
    const duplicates = fieldNames.filter((name, index) => fieldNames.indexOf(name) !== index);
    
    if (duplicates.length > 0) {
      console.log(`\n发现重复字段: ${[...new Set(duplicates)].join(', ')}`);
      
      // 显示重复字段的详细信息
      [...new Set(duplicates)].forEach(dupName => {
        console.log(`\n字段 "${dupName}" 的所有出现:`);
        table81.fields.forEach((field, index) => {
          if (field.name === dupName) {
            console.log(`  位置 ${index + 1}: 序号=${field.sequence}, 数据类型=${field.dataType}, 来源=${field.dataSource}`);
          }
        });
      });
    }
  } else {
    console.log('\n未找到 table_c81');
  }
}

main();
